<template>
  <view class="detail-page">
    <!-- 使用通用导航栏组件 -->
    <NavBar @back="goBack" />

    <!-- 可滚动区域：top/bottom 用来确保 scroll-view 真正可滚动 -->
    <scroll-view scroll-y class="scroll-box" @scroll="handleScroll">
      <view class="content" :style="{ paddingBottom: bottomActionsHeight + 'px' }">
        <!-- 题目标题 -->
        <view class="question-section" v-if="questionData.title">
          <text class="question-title">{{ questionData.id }}、{{ questionData.title }}</text>
        </view>

        <!-- 答案内容 -->
        <view class="answer-section" v-if="questionData.answer">
          <mp-html 
            :content="questionData.answer"
            :show-with-animation="true"
            :lazy-load="true"
            :markdown="true" 
          />
        </view>
        
        <!-- 加载中状态 -->
        <view v-if="loading" class="loading-section">
          <text class="loading-text">加载中...</text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏：固定在页面底部，添加 hide 类来做动画 -->
    <view :class="['bottom-actions', { hide: !showBottomActions }]">
      <view class="action-group">
        <view class="action-item" @click="toggleCollect">
          <SvgIcon :name="questionData.isFavorited ? 'save2' : 'save'" :size="20" />
          <text class="action-text">收藏</text>
        </view>
        <view class="action-item" @click="toggleLike">
          <SvgIcon :name="questionData.isLiked ? 'like2' : 'like'" :size="20" />
          <text class="action-text">点赞</text>
        </view>
      </view>
      <view class="nav-buttons">
        <view class="nav-btn prev-btn" @click="goToPrev">上一题</view>
        <view class="nav-btn next-btn" @click="goToNext">下一题</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useNavBar } from '@/hooks/useNavBar'
import { getInterviewDetail, likeInterview, favoriteInterview, type Interview } from '@/api/interview'
import NavBar from '@/components/NavBar.vue'
import SvgIcon from '@/components/SvgIcon.vue'

const { statusBarHeight, navBarHeight } = useNavBar()

// 控制底部栏显示/隐藏
const showBottomActions = ref(true)
let lastScrollTop = 0

// 根据你样式里 bottom-actions 的实际高度设定 (px)
// 你可以调整这个值（比如 100、120），以避免内容被遮挡
const bottomActionsHeight = 110

// 题目数据
const questionData = ref<Interview>({
  id: 0,
  title: '',
  question: '',
  answer: '',
  difficulty: 1,
  categoryId: 1,
  requirePremium: false,
  isLiked: false,
  isFavorited: false,
  likeCount: 0,
  favoriteCount: 0,
  viewCount: 0,
  createTime: '',
  updatedTime: '',
  previousId: null,
  nextId: null
})

// 加载状态
const loading = ref(false)


/**
 * 兼容性更好的滚动处理：
 * - uni-app 的 scroll-view 在大多数平台里把 scrollTop 放在 e.detail.scrollTop
 * - H5 平台可能是 e.target.scrollTop
 */
const handleScroll = (e: any) => {
  const currentScrollTop = e?.detail?.scrollTop ?? e?.target?.scrollTop ?? 0
  // debug 打印，确保触发
  console.log('[handleScroll] currentScrollTop:', currentScrollTop, e)

  // 阈值 10px，避免抖动频繁触发
  if (currentScrollTop > lastScrollTop + 10) {
    // 向下滚动 -> 隐藏
    showBottomActions.value = false
  } else if (currentScrollTop < lastScrollTop - 10) {
    // 向上滚动 -> 显示
    showBottomActions.value = true
  }
  lastScrollTop = currentScrollTop
}

// 使用 uniapp 的 onLoad 生命周期获取页面参数
onLoad((options) => {
  console.log('页面参数:', options)
  if (options?.id) {
    loadQuestionData(parseInt(options.id))
  }
})

// ---------- 业务方法（你原来的逻辑） ----------
const loadQuestionData = async (id: number) => {
    // 这里保留你的模拟逻辑或改成真实请求
    const res = await getInterviewDetail(id)
    console.log('API 响应:', res)
    questionData.value = res.data
}
const goBack = () => uni.navigateBack()
const toggleCollect = async () => {
  try {
    const res = await favoriteInterview(questionData.value.id)
    if (res.code === 200) {
      questionData.value.isFavorited = !questionData.value.isFavorited
      questionData.value.isFavorited ? questionData.value.favoriteCount++ : questionData.value.favoriteCount--
      uni.showToast({
        title: questionData.value.isFavorited ? '已收藏' : '取消收藏',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  }
}

const toggleLike = async () => {
  try {
    const res = await likeInterview(questionData.value.id)
    if (res.code === 200) {
      questionData.value.isLiked = !questionData.value.isLiked
      questionData.value.isLiked ? questionData.value.likeCount++ : questionData.value.likeCount--
      uni.showToast({
        title: questionData.value.isLiked ? '已点赞' : '取消点赞',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  }
}
const goToPrev = () => {
  const prevId = questionData.value.previousId
  if (prevId) {
    loadQuestionData(prevId)
  } else {
    uni.showToast({ title: '没有上一题了', icon: 'none' })
  }
}
const goToNext = () => {
  const nextId = questionData.value.nextId
  if (nextId) {
    loadQuestionData(nextId)
  } else {
    uni.showToast({ title: '没有下一题了', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>
.detail-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh);
}

/* 移除原有的导航栏样式，现在使用组件 */

/* 主滚动区域：绝对定位，上距为导航高度，下距为底部操作栏高度 */
.scroll-box {
  flex: 1;
  /* top/bottom 由 template inline style 控制以确保 js 里数值生效 */
  overflow: auto;
}

/* 内容里的 padding-bottom 防止底部操作栏遮挡内容 */
.content {
  padding: 0rpx 30rpx;
}

/* 题目和答案样式保持你的原样 */
.question-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  margin: 30rpx 0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

  .question-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #1f2937;
    line-height: 1.6;
  }
}

.answer-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 15px;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

  .answer-content {
    font-size: 28rpx;
    color: #374151;
    line-height: 1.8;
  }
}

.loading-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  margin: 30rpx 0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  text-align: center;

  .loading-text {
    font-size: 28rpx;
    color: #6b7280;
  }
}

/* 底部操作栏：固定，隐藏用 transform 动画 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #e5e7eb;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform 0.28s ease-in-out;
  z-index: 30;

  &.hide {
    transform: translateY(110%);
    /* 隐藏时向下移出视口 */
  }

  .action-group {
    display: flex;
    gap: 40rpx;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8rpx;

      .action-icon {
        font-size: 40rpx;
      }

      .action-text {
        font-size: 24rpx;
        color: #6b7280;
      }
    }
  }

  .nav-buttons {
    display: flex;
    gap: 20rpx;

    .nav-btn {
      padding: 10px 28px;
      border-radius: 50rpx;
      font-size: 28rpx;
      border: none;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
    }

    .prev-btn {
      background: #f3f4f6;
      color: #6b7280;
    }

    .next-btn {
      background: linear-gradient(90deg, #7f66f0, #a855f7);
      color: #fff;
    }
  }
}
</style>
